package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.dto.PageResult;
import com.itheima.dto.QueryPageBean;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 用户服务
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;


    //根据用户名查询数据库获取用户信息和关联的角色信息，同时需要查询角色关联的权限信息
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);//查询用户基本信息，不包含用户的角色
        if (user == null) {
            return null;
        }
        Integer userId = user.getId();
        //根据用户ID查询对应的角色
        Set<Role> roles = roleDao.findByUserId(userId);
        for (Role role : roles) {
            Integer roleId = role.getId();
            //根据角色ID查询关联的权限
            Set<Permission> permissions = permissionDao.findByRoleId(roleId);
            role.setPermissions(permissions);//让角色关联权限
        }
        user.setRoles(roles);//让用户关联角色
        return user;
    }

    public User findUserByUsername(String username) {
        return userDao.findDetailByUsername(username);
    }


    @Override
    public List<Map> findMeauByUsername(String username) {
        List<Map> lists = new ArrayList<>();
        int id = 1;
        List<User> mapList = userDao.findMeauByUsername(username);
        for (User user : mapList) {
            Set<Role> roles = user.getRoles();
            for (Role role : roles) {
                LinkedHashSet<Menu> menus = role.getMenus();
                for (Menu menu : menus) {

                    Map map = new HashMap();
                    map.put("id", id);
                    map.put("path", menu.getPath());
                    map.put("name", menu.getName());
                    map.put("icon", menu.getIcon());
                    map.put("priority", menu.getPriority());
                    map.put("parentMenuId", menu.getParentMenuId());
                    map.put("level", menu.getLevel());
                   /* List<Menu> children = menu.getChildren();
                    List clits = new ArrayList<>();
                    for (Menu child : children) {
                        Map mapc = new HashMap();
                        mapc.put("path", child.getPath());
                        mapc.put("title", child.getName());
                        mapc.put("linkUrl", child.getLinkUrl());
                        mapc.put("children", child.getChildren());
                        clits.add(mapc);
                    }
                    map.put("children", clits);*/
                    if (menu.getParentMenuId() == null) {
                        List<Menu> children = menu.getChildren();
                        if (children.size() > 0) {
                            findChildren(map, children, id);
                        }
                    }
                    lists.add(map);
                    id++;
                }
            }
        }
        return lists;
    }


    public List findChildren(Map map, List<Menu> children, Integer id) {
        List clits = new ArrayList<>();

        for (Menu child : children) {
            Map mapc = new HashMap();
            mapc.put("id", (id * 10) + 1);
            mapc.put("path", child.getPath());
            mapc.put("name", child.getName());
            mapc.put("linkUrl", child.getLinkUrl());
            mapc.put("priority", child.getPriority());
            mapc.put("parentMenuId", child.getParentMenuId());
            mapc.put("level", child.getLevel());
            if (child.getChildren().size() != 0) {
                List m = findChildren(mapc, child.getChildren(), id);
                mapc.put("children", m);
            }

            clits.add(mapc);
            id++;
        }
        map.put("children", clits);
        return clits;
    }


    /**
     * 分页查询所有的角色
     *
     * @param queryPageBean
     * @return
     */
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        String queryString = queryPageBean.getQueryString();
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        Page<User> pages = PageHelper.startPage(currentPage, pageSize);
        pages = userDao.findAllUser(queryString);
        return new PageResult(pages.getTotal(), pages.getResult());
    }


    /**
     * 添加一个的用户
     *
     * @param
     * @return
     */
    public void add(User user, Integer[] roleIds) {
        //基本信息的填写,新增一个用户
        userDao.add(user);
        //得到最新添加角色的id
        Integer id = user.getId();
        //操作关联关系表,新增角色添加了哪些权限
        if (roleIds != null && roleIds.length != 0) {
            addRoleIds(roleIds, id);
        }
    }


    /**
     * 操作关联关系表,新增角色添加了哪些权限
     *
     * @param roleIds
     * @param id
     */
    private void addRoleIds(Integer[] roleIds, Integer id) {

        userDao.addUserAndRoleAssociation(roleIds, id);
    }


    /**
     * 用于编辑用户时候基本的数据回显
     *
     * @param
     * @param id
     */
    public User findById(Integer id) {
        User user = userDao.findUserById(id);
        return user;
    }

    /**
     * 用于编辑用户时候查看此用户关联了哪些角色
     *
     * @param
     * @param id
     */
    public List<Integer> findRoleIdsByUserId(Integer id) {

        return userDao.findRoleIdsByUserId(id);
    }

    /**
     * 用于编辑用户
     *
     * @param
     * @param
     */
    public void edit(User u, Integer[] roleIds)  {
        Integer id = u.getId();
        //删除和角色的关联关系
        userDao.deleteAndRoleAssociation(id);
        if (roleIds != null && roleIds.length > 0) {
            //用于重新建立角色和权限的关联关系
            addRoleIds(roleIds, id);
        }
        //角色基本数据的填写
        userDao.edit(u);
    }

    /**
     * 用于删除一个用户
     *
     * @param
     * @param
     */
    public void delete(Integer id) {
        //先清理关联关系
        userDao.deleteAndRoleAssociation(id);
        userDao.delete(id);
    }
}
